home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 7 / Apprentice-Release7.iso / Source Code / C / Applications / Python 1.4 / Python 1.4 source / Mac / Python / macglue.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-09-23  |  20.9 KB  |  930 lines  |  [TEXT/CWIE]

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its 
  8. documentation for any purpose and without fee is hereby granted, 
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in 
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI not be used in advertising or publicity pertaining to
  13. distribution of the software without specific, written prior permission.
  14.  
  15. STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  16. THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  17. FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  18. FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  19. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  20. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  21. OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  22.  
  23. ******************************************************************/
  24.  
  25. #ifdef __CFM68K__
  26. /* cfm68k InterfaceLib exports GetEventQueue, but Events.h doesn't know this
  27. ** and defines it as GetEvQHdr (which is correct for PPC). This fix is for
  28. ** CW9, check that the workaround is still needed for the next release.
  29. */
  30. #define GetEvQHdr GetEventQueue
  31. #endif /* __CFM68K__ */
  32.  
  33. #include <Events.h>
  34.  
  35. #ifdef __CFM68K__
  36. #undef GetEventQueue
  37. #endif /* __CFM68K__ */
  38.  
  39. #include "Python.h"
  40.  
  41. #include "macglue.h"
  42. #include "marshal.h"
  43. #include "import.h"
  44.  
  45. #include "pythonresources.h"
  46.  
  47. #include <OSUtils.h> /* for Set(Current)A5 */
  48. #include <Files.h>
  49. #include <StandardFile.h>
  50. #include <Resources.h>
  51. #include <Memory.h>
  52. #include <Windows.h>
  53. #include <Desk.h>
  54. #include <Traps.h>
  55. #include <Processes.h>
  56. #include <Fonts.h>
  57. #include <Menus.h>
  58. #include <TextUtils.h>
  59. #ifdef THINK_C
  60. #include <OSEvents.h> /* For EvQElPtr */
  61. #endif
  62. #ifdef __MWERKS__
  63. #include <SIOUX.h>
  64. #endif
  65. #ifdef USE_GUSI
  66. #include <TFileSpec.h> /* For Path2FSSpec */
  67. #include <LowMem.h> /* For SetSFCurDir, etc */
  68. #include <GUSI.h>
  69. #endif
  70.  
  71. /* The ID of the Sioux apple menu */
  72. #define SIOUX_APPLEID    32000
  73.  
  74. #ifndef HAVE_UNIVERSAL_HEADERS
  75. #define GetResourceSizeOnDisk(x) SizeResource(x)
  76. typedef DlgHookYDProcPtr DlgHookYDUPP;
  77. #define NewDlgHookYDProc(userRoutine) ((DlgHookYDUPP) (userRoutine))
  78. typedef FileFilterYDProcPtr FileFilterYDUPP;
  79. #endif
  80.  
  81. #include <signal.h>
  82. #include <stdio.h>
  83.  
  84. /*
  85. ** When less than this amount of stackspace is left we
  86. ** raise a MemoryError.
  87. */
  88. #ifndef MINIMUM_STACK_SIZE
  89. #ifdef __powerc
  90. #define MINIMUM_STACK_SIZE 8192
  91. #else
  92. #define MINIMUM_STACK_SIZE 4096
  93. #endif
  94. #endif
  95.  
  96. /*
  97. ** We have to be careful, since we can't handle
  98. ** things like updates (and they'll keep coming back if we don't
  99. ** handle them). Note that we don't know who has windows open, so
  100. ** even handing updates off to SIOUX under MW isn't going to work.
  101. */
  102. #define MAINLOOP_EVENTMASK (mDownMask|keyDownMask|osMask)
  103.  
  104. #include <signal.h>
  105.  
  106. /* XXX We should include Errors.h here, but it has a name conflict
  107. ** with the python errors.h. */
  108. #define fnfErr -43
  109.  
  110. /* Declared in macfsmodule.c: */
  111. extern FSSpec *mfs_GetFSSpecFSSpec();
  112.  
  113. /* Interrupt code variables: */
  114. static int interrupted;            /* Set to true when cmd-. seen */
  115. static RETSIGTYPE intcatcher Py_PROTO((int));
  116.  
  117. static void PyMac_DoYield Py_PROTO((int));
  118.  
  119. /*
  120. ** We attempt to be a good citizen by giving up the CPU periodically.
  121. ** When in the foreground we do this less often and for shorter periods
  122. ** than when in the background. At this time we also check for events and
  123. ** pass them off to SIOUX, if compiling with mwerks.
  124. ** The counts here are in ticks of 1/60th second.
  125. ** XXXX The initial values here are not based on anything.
  126. ** FG-python gives up the cpu for 1/60th 5 times per second,
  127. ** BG-python for .2 second 10 times per second.
  128. */
  129. static long interval_fg = 12;
  130. static long interval_bg = 6;
  131. static long yield_fg = 1;
  132. static long yield_bg = 2;
  133. static long lastyield;
  134. static int in_foreground;
  135.  
  136. /* 
  137. ** When > 0, do full scanning for events (program is not event aware)
  138. ** when == 0, only scan for Command-period
  139. ** when < 0, don't do any event scanning 
  140. */
  141. int PyMac_DoYieldEnabled = 1;
  142.  
  143. /*
  144. ** Workaround for sioux/gusi combo: set when we are exiting
  145. */
  146. int PyMac_ConsoleIsDead;
  147.  
  148. /*
  149. ** Some stuff for our GetDirectory and PromptGetFile routines
  150. */
  151. struct hook_args {
  152.     int selectcur_hit;        /* Set to true when "select current" selected */
  153.     char *prompt;            /* The prompt */
  154. };
  155. static DlgHookYDUPP myhook_upp;
  156. static int upp_inited = 0;
  157.  
  158. #ifdef USE_GUSI
  159. /*
  160. ** GUSI (1.6.0 and earlier, at the least) do not set the MacOS idea of
  161. ** the working directory. Hence, we call this routine after each call
  162. ** to chdir() to rectify things.
  163. */
  164. void
  165. PyMac_FixGUSIcd()
  166. {
  167.     WDPBRec pb;
  168.     FSSpec curdirfss;
  169.     
  170.     if ( Path2FSSpec(":x", &curdirfss) != noErr ) 
  171.         return;
  172.     
  173.     /* Set MacOS "working directory" */
  174.     pb.ioNamePtr= "\p";
  175.     pb.ioVRefNum= curdirfss.vRefNum;
  176.     pb.ioWDDirID= curdirfss.parID;
  177.     if (PBHSetVol(&pb, 0) != noErr)
  178.         return;
  179. }
  180.  
  181. /*
  182. ** SpinCursor (needed by GUSI) drags in heaps of stuff, so we
  183. ** provide a dummy here.
  184. */
  185. void SpinCursor(short x) { /* Dummy */ }
  186.  
  187. /*
  188. ** Replacement GUSI Spin function
  189. */
  190. static int
  191. PyMac_GUSISpin(spin_msg msg, long arg)
  192. {
  193.     static Boolean            inForeground    =    true;
  194.     int                        maysleep;
  195.  
  196.     if (PyMac_ConsoleIsDead) return 0;
  197. #if 0
  198.     if (inForeground)
  199.         SpinCursor(msg == SP_AUTO_SPIN ? short(arg) : 1);
  200. #endif
  201.  
  202.     if (interrupted) return -1;
  203.  
  204.     if ( msg == SP_AUTO_SPIN || ((msg==SP_SLEEP||msg==SP_SELECT) && arg <= yield_fg))
  205.         maysleep = 0;
  206.     else
  207.         maysleep = 0;
  208.  
  209.     PyMac_DoYield(maysleep);
  210.  
  211.     return 0;
  212. }
  213.  
  214. void
  215. PyMac_SetGUSISpin() {
  216.     GUSISetHook(GUSI_SpinHook, (GUSIHook)PyMac_GUSISpin);
  217. }
  218.  
  219. #endif
  220.  
  221.  
  222. /* Convert C to Pascal string. Returns pointer to static buffer. */
  223. unsigned char *
  224. Pstring(char *str)
  225. {
  226.     static Str255 buf;
  227.     int len;
  228.  
  229.     len = strlen(str);
  230.     if (len > 255)
  231.         len = 255;
  232.     buf[0] = (unsigned char)len;
  233.     strncpy((char *)buf+1, str, len);
  234.     return buf;
  235. }
  236.  
  237. /* Like strerror() but for Mac OS error numbers */
  238. char *PyMac_StrError(int err)
  239. {
  240.     static char buf[256];
  241.     Handle h;
  242.     char *str;
  243.     
  244.     h = GetResource('Estr', err);
  245.     if ( h ) {
  246.         HLock(h);
  247.         str = (char *)*h;
  248.         memcpy(buf, str+1, (unsigned char)str[0]);
  249.         buf[(unsigned char)str[0]] = '\0';
  250.         HUnlock(h);
  251.         ReleaseResource(h);
  252.     } else {
  253.         sprintf(buf, "Mac OS error code %d", err);
  254.     }
  255.     return buf;
  256. }
  257.  
  258. /* Exception object shared by all Mac specific modules for Mac OS errors */
  259. PyObject *PyMac_OSErrException;
  260.  
  261. /* Initialize and return PyMac_OSErrException */
  262. PyObject *
  263. PyMac_GetOSErrException()
  264. {
  265.     if (PyMac_OSErrException == NULL)
  266.         PyMac_OSErrException = PyString_FromString("Mac OS Error");
  267.     return PyMac_OSErrException;
  268. }
  269.  
  270. /* Set a MAC-specific error from errno, and return NULL; return None if no error */
  271. PyObject * 
  272. PyErr_Mac(PyObject *eobj, int err)
  273. {
  274.     char *msg;
  275.     PyObject *v;
  276.     
  277.     if (err == 0 && !PyErr_Occurred()) {
  278.         Py_INCREF(Py_None);
  279.         return Py_None;
  280.     }
  281.     if (err == -1 && PyErr_Occurred())
  282.         return NULL;
  283.     msg = PyMac_StrError(err);
  284.     v = Py_BuildValue("(is)", err, msg);
  285.     PyErr_SetObject(eobj, v);
  286.     Py_DECREF(v);
  287.     return NULL;
  288. }
  289.  
  290. /* Call PyErr_Mac with PyMac_OSErrException */
  291. PyObject *
  292. PyMac_Error(OSErr err)
  293. {
  294.     return PyErr_Mac(PyMac_GetOSErrException(), err);
  295. }
  296.  
  297. #ifdef USE_STACKCHECK
  298. /* Check for stack overflow */
  299. int
  300. PyOS_CheckStack()
  301. {
  302.     long left;
  303.     
  304.     left = StackSpace();
  305.     if ( left < MINIMUM_STACK_SIZE )
  306.         return -1;
  307.     return 0;
  308. }
  309. #endif /* USE_STACKCHECK */
  310.  
  311. /* The catcher routine (which may not be used for all compilers) */
  312. static RETSIGTYPE
  313. intcatcher(sig)
  314.     int sig;
  315. {
  316.     interrupted = 1;
  317.     signal(SIGINT, intcatcher);
  318. }
  319.  
  320. void
  321. PyOS_InitInterrupts()
  322. {
  323.     if (signal(SIGINT, SIG_IGN) != SIG_IGN)
  324.         signal(SIGINT, intcatcher);
  325. }
  326.  
  327. /*
  328. ** This routine scans the event queue looking for cmd-.
  329. ** This is the only way to get an interrupt under THINK (since it
  330. ** doesn't do SIGINT handling), but is also used under MW, when
  331. ** the full-fledged event loop is disabled. This way, we can at least
  332. ** interrupt a runaway python program.
  333. */
  334. static void
  335. scan_event_queue(flush)
  336.     int flush;
  337. {
  338.     register EvQElPtr q;
  339.     
  340.     q = (EvQElPtr) GetEventQueue()->qHead;
  341.     
  342.     for (; q; q = (EvQElPtr)q->qLink) {
  343.         if (q->evtQWhat == keyDown &&
  344.                 (char)q->evtQMessage == '.' &&
  345.                 (q->evtQModifiers & cmdKey) != 0) {
  346.             if ( flush )
  347.                 FlushEvents(keyDownMask, 0);
  348.             interrupted = 1;
  349.             break;
  350.         }
  351.     }
  352. }
  353.  
  354. int
  355. PyOS_InterruptOccurred()
  356. {
  357.     if (PyMac_DoYieldEnabled < 0)
  358.         return 0;
  359. #ifdef THINK_C
  360.     scan_event_queue(1);
  361. #endif
  362.     PyMac_Yield();
  363.     if (interrupted) {
  364.         interrupted = 0;
  365.         return 1;
  366.     }
  367.     return 0;
  368. }
  369.  
  370. /* intrpeek() is like intrcheck(), but it doesn't flush the events. The
  371. ** idea is that you call intrpeek() somewhere in a busy-wait loop, and return
  372. ** None as soon as it returns 1. The mainloop will then pick up the cmd-. soon
  373. ** thereafter.
  374. */
  375. static int
  376. intrpeek()
  377. {
  378. #ifdef THINK_C
  379.     scan_event_queue(0);
  380. #endif
  381.     return interrupted;
  382. }
  383.  
  384. /* Check whether we are in the foreground */
  385. int
  386. PyMac_InForeground()
  387. {
  388.     static ProcessSerialNumber ours;
  389.     static inited;
  390.     ProcessSerialNumber curfg;
  391.     Boolean eq;
  392.     
  393.     if ( inited == 0 )
  394.         (void)GetCurrentProcess(&ours);
  395.     inited = 1;
  396.     if ( GetFrontProcess(&curfg) < 0 )
  397.         eq = 1;
  398.     else if ( SameProcess(&ours, &curfg, &eq) < 0 )
  399.         eq = 1;
  400.     return (int)eq;
  401.  
  402. }
  403.  
  404. /*
  405. ** Set yield timeouts
  406. */
  407. void
  408. PyMac_SetYield(long fgi, long fgy, long bgi, long bgy)
  409. {
  410.     interval_fg = fgi;
  411.     yield_fg = fgy;
  412.     interval_bg = bgi;
  413.     yield_bg = bgy;
  414. }
  415.  
  416. /*
  417. ** Handle an event, either one found in the mainloop eventhandler or
  418. ** one passed back from the python program.
  419. */
  420. void
  421. PyMac_HandleEvent(evp)
  422.     EventRecord *evp;
  423. {
  424.             
  425. #ifdef __MWERKS__
  426.     {
  427.         int siouxdidit;
  428.  
  429.         /* If SIOUX wants it we're done */
  430.         siouxdidit = SIOUXHandleOneEvent(evp);
  431.         if ( siouxdidit )
  432.             return;
  433.     }
  434. #else
  435.     /* Other compilers are just unlucky: we only weed out clicks in other applications */
  436.     if ( evp->what == mouseDown ) {
  437.         WindowPtr wp;
  438.         
  439.         if ( FindWindow(evp->where, &wp) == inSysWindow ) {
  440.             SystemClick(evp, wp);
  441.             return;
  442.         }
  443.     }
  444. #endif /* !__MWERKS__ */
  445. }
  446.  
  447. /*
  448. ** Yield the CPU to other tasks.
  449. */
  450. static void
  451. PyMac_DoYield(int maysleep)
  452. {
  453.     EventRecord ev;
  454.     long yield;
  455.     static int no_waitnextevent = -1;
  456.     int gotone;
  457.     
  458.     if ( no_waitnextevent < 0 ) {
  459.         no_waitnextevent = (NGetTrapAddress(_WaitNextEvent, ToolTrap) ==
  460.                             NGetTrapAddress(_Unimplemented, ToolTrap));
  461.     }
  462.  
  463.     lastyield = TickCount();
  464. #ifndef THINK_C
  465.     /* Under think this has been done before in intrcheck() or intrpeek() */
  466.     if (PyMac_DoYieldEnabled >= 0)
  467.         scan_event_queue(0);
  468. #endif
  469.     if (PyMac_DoYieldEnabled == 0)
  470.         return;
  471.         
  472.     in_foreground = PyMac_InForeground();
  473.     if ( maysleep ) {
  474.         if ( in_foreground )
  475.             yield = yield_fg;
  476.         else
  477.             yield = yield_bg;
  478.     } else {
  479.         yield = 0;
  480.     }
  481.         
  482.     while ( 1 ) {
  483.         if ( no_waitnextevent ) {
  484.             SystemTask();
  485.             gotone = GetNextEvent(MAINLOOP_EVENTMASK, &ev);
  486.         } else {
  487.             gotone = WaitNextEvent(MAINLOOP_EVENTMASK, &ev, yield, NULL);
  488.         }    
  489.         /* Get out quickly if nothing interesting is happening */
  490.         if ( !gotone || ev.what == nullEvent )
  491.             break;
  492.         PyMac_HandleEvent(&ev);
  493.     }
  494. }
  495.  
  496. /*
  497. ** Yield the CPU to other tasks if opportune
  498. */
  499. void
  500. PyMac_Yield() {
  501.     long iv;
  502.     
  503.     if ( in_foreground )
  504.         iv = interval_fg;
  505.     else
  506.         iv = interval_bg;
  507.     if ( TickCount() > lastyield + iv )
  508.         PyMac_DoYield(1);
  509. }
  510.  
  511. #ifdef USE_MACTCP
  512. /*
  513. ** Idle routine for busy-wait loops.
  514. ** Gives up CPU, handles events and returns true if an interrupt is pending
  515. ** (but not actually handled yet).
  516. */
  517. int
  518. PyMac_Idle()
  519. {
  520.     PyMac_DoYield(1);
  521.     return intrpeek();
  522. }
  523. #endif
  524.  
  525. /*
  526. ** Install our menu bar.
  527. */
  528. void
  529. PyMac_InitMenuBar()
  530. {
  531.     Handle bar;
  532.     MenuHandle applemenu;
  533.     
  534.     if ( (bar=GetMenuBar()) == NULL ) return;
  535.     if ( (applemenu=GetMHandle(SIOUX_APPLEID)) == NULL ) return;
  536.     SetMenuItemText(applemenu, 1, "\pAbout Python...");
  537. }
  538.  
  539. /*
  540. ** Our replacement about box
  541. */
  542. void
  543. SIOUXDoAboutBox(void)
  544. {
  545.     DialogPtr theDialog;
  546.     WindowRef theWindow;
  547.     CGrafPtr thePort;
  548.     short item;
  549.     short xpos, ypos, width, height, swidth, sheight;
  550.     
  551.     if( (theDialog = GetNewDialog(ABOUT_ID, NULL, (WindowPtr)-1)) == NULL )
  552.         return;
  553.     theWindow = GetDialogWindow(theDialog);
  554.     thePort = GetWindowPort(theWindow);
  555.     width = thePort->portRect.right - thePort->portRect.left;
  556.     height = thePort->portRect.bottom - thePort->portRect.top;
  557.     swidth = qd.screenBits.bounds.right - qd.screenBits.bounds.left;
  558.     sheight = qd.screenBits.bounds.bottom - qd.screenBits.bounds.top - LMGetMBarHeight();
  559.     xpos = (swidth-width)/2;
  560.     ypos = (sheight-height)/5 + LMGetMBarHeight();
  561.     MoveWindow(theWindow, xpos, ypos, 0);
  562.     ShowWindow(theWindow);
  563.     ModalDialog(NULL, &item);
  564.     DisposeDialog(theDialog);
  565. }
  566.  
  567. /*
  568. ** Returns true if the argument has a resource fork, and it contains
  569. ** a 'PYC ' resource of the correct name
  570. */
  571. int
  572. PyMac_FindResourceModule(module, filename)
  573. char *module;
  574. char *filename;
  575. {
  576.     FSSpec fss;
  577.     FInfo finfo;
  578.     short oldrh, filerh;
  579.     int ok;
  580.     Handle h;
  581.     
  582.     if ( FSMakeFSSpec(0, 0, Pstring(filename), &fss) != noErr )
  583.         return 0;            /* It doesn't exist */
  584.     if ( FSpGetFInfo(&fss, &finfo) != noErr )
  585.         return 0;            /* shouldn't happen, I guess */
  586.     oldrh = CurResFile();
  587.     filerh = FSpOpenResFile(&fss, fsRdPerm);
  588.     if ( filerh == -1 )
  589.         return 0;
  590.     UseResFile(filerh);
  591.     SetResLoad(0);
  592.     h = Get1NamedResource('PYC ', Pstring(module));
  593.     SetResLoad(1);
  594.     ok = (h != NULL);
  595.     CloseResFile(filerh);
  596.     UseResFile(oldrh);
  597.     return ok;
  598. }
  599.  
  600. /*
  601. ** Load the specified module from a resource
  602. */
  603. PyObject *
  604. PyMac_LoadResourceModule(module, filename)
  605. char *module;
  606. char *filename;
  607. {
  608.     FSSpec fss;
  609.     FInfo finfo;
  610.     short oldrh, filerh;
  611.     Handle h;
  612.     OSErr err;
  613.     PyObject *m, *co;
  614.     long num, size;
  615.     
  616.     if ( (err=FSMakeFSSpec(0, 0, Pstring(filename), &fss)) != noErr )
  617.         goto error;
  618.     if ( (err=FSpGetFInfo(&fss, &finfo)) != noErr )
  619.         goto error;
  620.     oldrh = CurResFile();
  621.     filerh = FSpOpenResFile(&fss, fsRdPerm);
  622.     if ( filerh == -1 ) {
  623.         err = ResError();
  624.         goto error;
  625.     }
  626.     UseResFile(filerh);
  627.     h = Get1NamedResource('PYC ', Pstring(module));
  628.     if ( h == NULL ) {
  629.         err = ResError();
  630.         goto error;
  631.     }
  632.     HLock(h);
  633.     /*
  634.     ** XXXX The next few lines are intimately tied to the format of pyc
  635.     ** files. I'm not sure whether this code should be here or in import.c -- Jack
  636.     */
  637.     size = GetHandleSize(h);
  638.     if ( size < 8 ) {
  639.         PyErr_SetString(PyExc_ImportError, "Resource too small");
  640.         co = NULL;
  641.     } else {
  642.         num = (*h)[0] & 0xff;
  643.         num = num | (((*h)[1] & 0xff) << 8);
  644.         num = num | (((*h)[2] & 0xff) << 16);
  645.         num = num | (((*h)[3] & 0xff) << 24);
  646.         if ( num != PyImport_GetMagicNumber() ) {
  647.             PyErr_SetString(PyExc_ImportError, "Bad MAGIC in resource");
  648.             co = NULL;
  649.         } else {
  650.             co = PyMarshal_ReadObjectFromString((*h)+8, size-8);
  651.         }
  652.     }
  653.     HUnlock(h);
  654.     CloseResFile(filerh);
  655.     UseResFile(oldrh);
  656.     if ( co ) {
  657.         m = PyImport_ExecCodeModule(module, co);
  658.         Py_DECREF(co);
  659.     } else {
  660.         m = NULL;
  661.     }
  662.     return m;
  663. error:
  664.     {
  665.         char buf[512];
  666.         
  667.         sprintf(buf, "%s: %s", filename, PyMac_StrError(err));
  668.         PyErr_SetString(PyExc_ImportError, buf);
  669.         return NULL;
  670.     }
  671. }
  672.  
  673. /*
  674. ** Helper routine for GetDirectory
  675. */
  676. static pascal short
  677. myhook_proc(short item, DialogPtr theDialog, struct hook_args *dataptr)
  678. {
  679.     if ( item == sfHookFirstCall && dataptr->prompt) {
  680.         Handle prompth;
  681.         short type;
  682.         Rect rect;
  683.         
  684.         GetDialogItem(theDialog, PROMPT_ITEM, &type, &prompth, &rect);
  685.         if ( prompth )
  686.             SetDialogItemText(prompth, (unsigned char *)dataptr->prompt);
  687.     } else
  688.     if ( item == SELECTCUR_ITEM ) {
  689.         item = sfItemCancelButton;
  690.         dataptr->selectcur_hit = 1;
  691.     }
  692.     return item;
  693. }    
  694.  
  695. /*
  696. ** Ask the user for a directory. I still can't understand
  697. ** why Apple doesn't provide a standard solution for this...
  698. */
  699. int
  700. PyMac_GetDirectory(dirfss, prompt)
  701.     FSSpec *dirfss;
  702.     char *prompt;
  703. {
  704.     static SFTypeList list = {'fldr', 0, 0, 0};
  705.     static Point where = {-1, -1};
  706.     StandardFileReply reply;
  707.     struct hook_args hook_args;
  708.     
  709.     if ( !upp_inited ) {
  710.         myhook_upp = NewDlgHookYDProc(myhook_proc);
  711.         upp_inited = 1;
  712.     }
  713.     if ( prompt && *prompt )
  714.         hook_args.prompt = (char *)Pstring(prompt);
  715.     else
  716.         hook_args.prompt = NULL;
  717.     hook_args.selectcur_hit = 0;
  718.     CustomGetFile((FileFilterYDUPP)0, 1, list, &reply, GETDIR_ID, where, myhook_upp,
  719.                 NULL, NULL, NULL, (void *)&hook_args);
  720.                 
  721.     reply.sfFile.name[0] = 0;
  722.     if( FSMakeFSSpec(reply.sfFile.vRefNum, reply.sfFile.parID, reply.sfFile.name, dirfss) )
  723.         return 0;
  724.     return hook_args.selectcur_hit;
  725. }
  726.  
  727. /*
  728. ** Slightly extended StandardGetFile: accepts a prompt */
  729. void PyMac_PromptGetFile(short numTypes, ConstSFTypeListPtr typeList, 
  730.         StandardFileReply *reply, char *prompt)
  731. {
  732.     static Point where = {-1, -1};
  733.     struct hook_args hook_args;
  734.     
  735.     if ( !upp_inited ) {
  736.         myhook_upp = NewDlgHookYDProc(myhook_proc);
  737.         upp_inited = 1;
  738.     }
  739.     if ( prompt && *prompt )
  740.         hook_args.prompt = (char *)Pstring(prompt);
  741.     else
  742.         hook_args.prompt = NULL;
  743.     hook_args.selectcur_hit = 0;
  744.     CustomGetFile((FileFilterYDUPP)0, numTypes, typeList, reply, GETFILEPROMPT_ID, where,
  745.                 myhook_upp, NULL, NULL, NULL, (void *)&hook_args);
  746. }
  747.  
  748. /* Convert a 4-char string object argument to an OSType value */
  749. int
  750. PyMac_GetOSType(PyObject *v, OSType *pr)
  751. {
  752.     if (!PyString_Check(v) || PyString_Size(v) != 4) {
  753.         PyErr_SetString(PyExc_TypeError,
  754.             "OSType arg must be string of 4 chars");
  755.         return 0;
  756.     }
  757.     memcpy((char *)pr, PyString_AsString(v), 4);
  758.     return 1;
  759. }
  760.  
  761. /* Convert an OSType value to a 4-char string object */
  762. PyObject *
  763. PyMac_BuildOSType(OSType t)
  764. {
  765.     return PyString_FromStringAndSize((char *)&t, 4);
  766. }
  767.  
  768. /* Convert an NumVersion value to a 4-element tuple */
  769. PyObject *
  770. PyMac_BuildNumVersion(NumVersion t)
  771. {
  772.     return Py_BuildValue("(hhhh)", t.majorRev, t.minorAndBugRev, t.stage, t.nonRelRev);
  773. }
  774.  
  775.  
  776. /* Convert a Python string object to a Str255 */
  777. int
  778. PyMac_GetStr255(PyObject *v, Str255 pbuf)
  779. {
  780.     int len;
  781.     if (!PyString_Check(v) || (len = PyString_Size(v)) > 255) {
  782.         PyErr_SetString(PyExc_TypeError,
  783.             "Str255 arg must be string of at most 255 chars");
  784.         return 0;
  785.     }
  786.     pbuf[0] = len;
  787.     memcpy((char *)(pbuf+1), PyString_AsString(v), len);
  788.     return 1;
  789. }
  790.  
  791. /* Convert a Str255 to a Python string object */
  792. PyObject *
  793. PyMac_BuildStr255(Str255 s)
  794. {
  795.     return PyString_FromStringAndSize((char *)&s[1], (int)s[0]);
  796. }
  797.  
  798.  
  799. /*
  800. ** Convert a Python object to an FSSpec.
  801. ** The object may either be a full pathname or a triple
  802. ** (vrefnum, dirid, path).
  803. ** NOTE: This routine will fail on pre-sys7 machines. 
  804. ** The caller is responsible for not calling this routine
  805. ** in those cases (which is fine, since everyone calling
  806. ** this is probably sys7 dependent anyway).
  807. */
  808. int
  809. PyMac_GetFSSpec(PyObject *v, FSSpec *fs)
  810. {
  811.     Str255 path;
  812.     short refnum;
  813.     long parid;
  814.     OSErr err;
  815.     FSSpec *fs2;
  816.  
  817.     /* first check whether it already is an FSSpec */
  818.     fs2 = mfs_GetFSSpecFSSpec(v);
  819.     if ( fs2 ) {
  820.         (void)FSMakeFSSpec(fs2->vRefNum, fs2->parID, fs2->name, fs);
  821.         return 1;
  822.     }
  823.     if ( PyString_Check(v) ) {
  824.         /* It's a pathname */
  825.         if( !PyArg_Parse(v, "O&", PyMac_GetStr255, &path) )
  826.             return 0;
  827.         refnum = 0; /* XXXX Should get CurWD here?? */
  828.         parid = 0;
  829.     } else {
  830.         if( !PyArg_Parse(v, "(hlO&); FSSpec should be fullpath or (vrefnum,dirid,path)",
  831.                             &refnum, &parid, PyMac_GetStr255, &path)) {
  832.             return 0;
  833.         }
  834.     }
  835.     err = FSMakeFSSpec(refnum, parid, path, fs);
  836.     if ( err && err != fnfErr ) {
  837.         PyErr_Mac(PyExc_ValueError, err);
  838.         return 0;
  839.     }
  840.     return 1;
  841. }
  842.  
  843.  
  844. /* Convert a Python object to a Rect.
  845.    The object must be a (left, top, right, bottom) tuple.
  846.    (This differs from the order in the struct but is consistent with
  847.    the arguments to SetRect(), and also with STDWIN). */
  848. int
  849. PyMac_GetRect(PyObject *v, Rect *r)
  850. {
  851.     return PyArg_Parse(v, "(hhhh)", &r->left, &r->top, &r->right, &r->bottom);
  852. }
  853.  
  854. /* Convert a Rect to a Python object */
  855. PyObject *
  856. PyMac_BuildRect(Rect *r)
  857. {
  858.     return Py_BuildValue("(hhhh)", r->left, r->top, r->right, r->bottom);
  859. }
  860.  
  861.  
  862. /* Convert a Python object to a Point.
  863.    The object must be a (h, v) tuple.
  864.    (This differs from the order in the struct but is consistent with
  865.    the arguments to SetPoint(), and also with STDWIN). */
  866. int
  867. PyMac_GetPoint(PyObject *v, Point *p)
  868. {
  869.     return PyArg_Parse(v, "(hh)", &p->h, &p->v);
  870. }
  871.  
  872. /* Convert a Point to a Python object */
  873. PyObject *
  874. PyMac_BuildPoint(Point p)
  875. {
  876.     return Py_BuildValue("(hh)", p.h, p.v);
  877. }
  878.  
  879.  
  880. /* Convert a Python object to an EventRecord.
  881.    The object must be a (what, message, when, (v, h), modifiers) tuple. */
  882. int
  883. PyMac_GetEventRecord(PyObject *v, EventRecord *e)
  884. {
  885.     return PyArg_Parse(v, "(hll(hh)h)",
  886.                        &e->what,
  887.                        &e->message,
  888.                        &e->when,
  889.                        &e->where.h,
  890.                        &e->where.v,                   
  891.                        &e->modifiers);
  892. }
  893.  
  894. /* Convert a Rect to an EventRecord object */
  895. PyObject *
  896. PyMac_BuildEventRecord(EventRecord *e)
  897. {
  898.     return Py_BuildValue("(hll(hh)h)",
  899.                          e->what,
  900.                          e->message,
  901.                          e->when,
  902.                          e->where.h,
  903.                          e->where.v,
  904.                          e->modifiers);
  905. }
  906.  
  907. /* Convert Python object to Fixed */
  908. int
  909. PyMac_GetFixed(PyObject *v, Fixed *f)
  910. {
  911.     double d;
  912.     
  913.     if( !PyArg_Parse(v, "d", &d))
  914.         return 0;
  915.     *f = (Fixed)(d * 0x10000);
  916.     return 1;
  917. }
  918.  
  919. /* Convert a Point to a Python object */
  920. PyObject *
  921. PyMac_BuildFixed(Fixed f)
  922. {
  923.     double d;
  924.     
  925.     d = f;
  926.     d = d / 0x10000;
  927.     return Py_BuildValue("d", d);
  928. }
  929.  
  930.